package abc.datasource;

import abc.utils.StringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.tx.LocalTxUtil;
import com.baomidou.dynamic.datasource.tx.TransactionContext;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class DynamicTransactionInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        DS ds = methodInvocation.getThis().getClass().getAnnotation(DS.class);
        if(ds!=null) {
            DynamicDataSourceContextHolder.setDataSourceType(ds.value());
        }
        else {
            DataSource dataSource = methodInvocation.getThis().getClass().getAnnotation(DataSource.class);
            if(dataSource!=null && StringUtil.isNotEmpty(dataSource.value())) {
                DynamicDataSourceContextHolder.setDataSourceType(dataSource.value());
            }
        }
        if (!StringUtil.isEmpty(TransactionContext.getXID())) {
            return methodInvocation.proceed();
        }
        boolean state = true;
        Object o;
        LocalTxUtil.startTransaction();
        try {
            o = methodInvocation.proceed();
        } catch (Exception e) {
            state = false;
            throw e;
        } finally {
            if (state) {
                LocalTxUtil.commit();
            } else {
                LocalTxUtil.rollback();
            }
        }
        return o;
    }
}
